<?php

namespace app\controller\merchant;

use app\BaseController;
use app\model\Area;
use app\model\Store;
use think\response\Json;

class MerchantStore extends BaseController
{
    public function add(): Json
    {
        if (!$this->request->isPost()) throw new \Exception('请求方式错误', 7001);
        return $this->success($this->app->make(Store::class)->updateOrAdd());
    }

    public function lst(): Json
    {
        return $this->success($this->app->make(Store::class)->getPage());
    }

    public function delete(): Json
    {
        if (!$this->request->isDelete()) throw new \Exception('请求方式错误', 7001);
        return $this->success($this->app->make(Store::class)->del());
    }

    public function info(): Json
    {
        return $this->success($this->app->make(Store::class)->detail());
    }

    public function uploadStore(): Json
    {
        if (!$this->request->isPost()) throw new \Exception('请求方式错误', 7001);
        $stores = $this->request->post("store");
        $pid = $this->request->post("pid");
        $area = $this->app->make(Area::class);
        $_data = array_map(function ($its) use ($area, $pid) {
            if (empty($its['省份']) || empty($its['城市']) || empty($its['地区'])) return null;
            $pro = $area->whereLike('name', '%' . $its['省份'] . '%')->where('level', '=', 1)->value('id');
            $city = $area->whereLike('name', '%' . $its['城市'] . '%')->where('level', '=', 2)->value('id');
            $area = $area->whereLike('name', '%' . $its['地区'] . '%')->where('level', '=', 3)->value('id');
            return [
                "name" => $its['门店名称'],
                "pro" => $pro,
                "city" => $city,
                "area" => $area,
                "address" => $its['地址'],
                "mobile" => $its['手机号'],
                "username" => $its['联系人'],
                'pid' => $pid
            ];
        }, $stores);
        $_data = array_filter($_data);
        if (empty($_data)) throw new \Exception('数据为空', 7001);
        $this->app->make(Store::class)->saveAll(array_values($_data));
        return $this->success($_data);
    }
}
